<template>
    <el-form :model="formParam" :rules="rulesInformation" ref="custForm" >
        <div style="display: flex;">
            <h2 style="flex: 1;text-align: center;">&nbsp;</h2>
            <div>
                <div><span style="line-height: 28px;width: 48px;text-align: left;display: inline-block;margin-right: 10px;">PORT </span>
                    <b style="display: inline-block;width: 160px;padding: 0 5px; text-align: center;">{{props.titleValue}}</b>
                </div>
                <div style="display: flex;margin-top: 6px;">
                    <span style="line-height: 28px;width: 48px;text-align: left;display: inline-block;margin-right: 10px;">BERTH</span>
                  
                        <el-form-item prop=""><el-input style="width:150px;" class="berth_text" v-model="formParam.berth" />
                        </el-form-item>
                </div>
            </div>
        </div>
        <el-table :data="recordData" class="detail-table" :span-method="arraySpanMethod" stripe :border="true">
            <el-table-column prop="name" label="" width="105" />
            <el-table-column :label="props.titleValue">
                <template #default="scope">
                    <el-form-item v-if="scope.$index == 0" prop="eta">
                        <el-date-picker type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                            v-model="formParam.eta" placeholder="Please select" />
                    </el-form-item>
                    <el-form-item v-if="scope.$index == 1" prop="ata">
                        <el-date-picker type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                            v-model="formParam.ata" placeholder="Please select" />
                    </el-form-item>
                    <el-form-item v-if="scope.$index == 2" prop="etd">
                        <el-date-picker type="date"     format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                            v-model="formParam.etd" placeholder="Please select" />
                    </el-form-item>
                    <el-form-item v-if="scope.$index == 3" prop="atd">
                        <el-date-picker type="datetime" format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                         v-model="formParam.atd" placeholder="Please select" />
                    </el-form-item>
                    <el-form-item v-if="scope.$index ==4" prop="activity" style="width: 60%;">
                        <el-select class="handle_activity" v-model="formParam.activity" multiple filterable  style="width: 100%;"  popper-class="custom-select-dropdown">
                            <el-option :key="index" :label="item" :value="index" v-for="(item,index) in activitys">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <!--  v-hasPermi="['schedule:general:edit']" -->
                    <div v-if="scope.$index==5">
                        <DragUpload
                        :multiple="false"
                        accept=".jpg,.jpeg,.png,.pdf,.docx,.txt"
                        :maxSize="1"
                        @upload-start="handleUploadStart"
                        @files-change="handleFilesChange"
                        @file-removed="handleFileRemoved($event,0)"
                        v-model="voyageSof"
                        :disabled="!hasTableEditAuth('schedule:general:edit')"
                        />
                    </div> 
                </template>
            </el-table-column>
            <el-table-column label="ANCHORAGE">
                <template #default="scope">
                    <el-form-item v-if="scope.$index==1">
                        <el-date-picker type="datetime" format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                            v-model="formParam.ataAnchorage" placeholder="Please select" />
                    </el-form-item>
                </template>
            </el-table-column>
            <el-table-column label="DRIFTING">
                <template #default="scope">
                    <div v-if="scope.$index==1">
                        <el-form-item>
                            <el-date-picker type="datetime" format="YYYY/MM/DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss" v-model="formParam.ataDrifting"
                                placeholder="Please select" />
                        </el-form-item>
                    </div>

                </template>
            </el-table-column>
            <el-table-column label="P/S ARRIVAL">
                <template #default="scope">
                    <el-form-item v-if="scope.$index==1" prop="">
                        <el-date-picker type="datetime" format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                            v-model="formParam.ataPsArrival" placeholder="Please select" />
                    </el-form-item>
                </template>
            </el-table-column>
            <el-table-column label="BERTH ARRIVAL">
                <template #default="scope">
                    <el-form-item v-if="scope.$index==1" prop="">
                        <el-date-picker type="datetime" format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                            v-model="formParam.ataBerth" placeholder="Please select" />
                    </el-form-item>
                </template>
            </el-table-column>
        </el-table>
    </el-form>
    <div class="pane-footer" v-hasPermi="['schedule:general:edit']">
        <el-button @click="cancelHandle" >{{ $t("ship.button.cancel") }}</el-button>
        <el-button type="primary"  @click="submitForm">{{ $t("ship.button.submit") }}</el-button>
    </div>
</template>
<script lang="ts" setup>
// @ts-nocheck
import { ref, onMounted, computed, reactive, nextTick, defineEmits } from "vue";
import service from "@/utils/request";
import {convertUrl} from "@/utils/tencentCos";
import { ElNotification, ElMessageBox } from "element-plus";
import { useRouter} from "vue-router";
import DragUpload from '@/components/FormDataIUpload/index.vue';
import {hasTableEditAuth} from "@/utils/auth";
const props = defineProps({
    data: {
        type: Object,
        default: () => { },
    },
    titleValue: {
        type: String,
        default: ''
    }
})
const route = useRoute()
console.log('[  route] >', route)
const emit = defineEmits(['saveOk','getDetail'])
const custForm = ref(null);

const initForm = reactive({
    id: null,
    eta: null,
    ata: null,
    ataAnchorage: null,
    ataDrifting: null,
    ataPsArrival: null,
    ataArrival: null,
    etd: null,
    atd: null,
    activity: []
});
const formParam = ref({
})

let recordData = ref([
    {
        name: 'ETA',
        ETA: null,
        ATA: null,
        ETD: null,
        ATD: '',
        ACTIVITY: '',
        VOYAGESOF: ''
    },
    {
        name: 'ATA',
        ETA: null,
        ATA: null,
        ETD: null,
        ATD: '',
        ACTIVITY: '',
        VOYAGESOF: ''
    },
    {
        name: 'ETD',
        ETA: null,
        ATA: null,
        ETD: null,
        ATD: '',
        ACTIVITY: '',
        VOYAGESOF: ''
    },
    {
        name: 'ATD',
        ETA: null,
        ATA: null,
        ETD: null,
        ATD: '',
        ACTIVITY: '',
        VOYAGESOF: ''
    },
    {
        name: 'ACTIVITY',
        ETA: null,
        ATA: null,
        ETD: null,
        ATD: '',
        ACTIVITY: '',
        VOYAGESOF: ''
    },
    {
        name: 'VOYAGE SOF',
        ETA: null,
        ATA: null,
        ETD: null,
        ATD: '',
        ACTIVITY: '',
        VOYAGESOF: ''
    }
])
const voyageSof=ref([])
watch(() => props.data, val => {
    if (Object.keys(val).length !== 0) {
    formParam.value = Object.assign(val, {})
    if(formParam.value.voyageSof){
        voyageSof.value=[{name:getFileName(formParam.value.voyageSof),url:formParam.value.voyageSof}]
    } 
    if(formParam.value.atd){
       if (/^\d{4}-\d{2}-\d{2}$/.test(formParam.value.atd)) {
            // 如果是日期格式，添加时间部分
            formParam.value.atd = formParam.value.atd + ' 00:00:00';
        }
    }
    return
}
}, { deep: true, immediate: true });

const activitys = ["LOADING", "DISCHARGING", "BUNKERING", "D/D or SURVEY", "CREW CHANGE","PASSING"]


// 表格验证
const rulesInformation = ref({
    eta: [
        { required: true, message: 'Please select' },
        {
            validator: (rule, value, callback) => {
                if (formParam.value.eta && formParam.value.etd) {
                    // if (new Date(formParam.value.eta).getTime() > new Date(formParam.value.etd).getTime()) {
                    //     callback(new Error('eta cannot be large than etd'));
                    // }
                }
                callback();
            }
        }],
    ata: [{ required: false, message: 'Please select' },
    {
        validator: (rule, value, callback) => {
            // if (formParam.value.ata && formParam.value.atd) {
            //     if (new Date(formParam.value.ata).getTime() > new Date(formParam.value.atd).getTime()) {
            //         callback(new Error('ata cannot be large than atd'));
            //     }
            // }
            callback();
        }
    }],
    etd: [
    {
        validator: (rule, value, callback) => {
            // if (formParam.value.eta && formParam.value.etd) {
            //     if (new Date(formParam.value.eta).getTime() > new Date(formParam.value.etd).getTime()) {
            //         callback(new Error('eta cannot be large than etd'));
            //     }
            // }
            callback();
        }
    }],
    atd: [{ required: false, message: 'Please select' }, {
        validator: (rule, value, callback) => {
            // if (formParam.value.ata && formParam.value.atd) {
            //     if (new Date(formParam.value.ata).getTime() > new Date(formParam.value.atd).getTime()) {
            //         callback(new Error('ata cannot be large than atd'));
            //     }
            // }
            callback();
        }
    }],
    activity: [{ required: true, message: 'Please select' }],
    ataDrifting: [{ required: true, message: 'Please select' }],
    ataPsArrival: [{ required: true, message: 'Please select' }],
    ataBerth: [{ required: true, message: 'Please select' }],
    berth: [{ required: true, message: 'Please Input' }],
});


const resetForm = () => {
    // @ts-ignore
    custForm.value.resetFields();
};

const submitForm = () => {
    // @ts-ignore  
    custForm.value.validate(async (valid) => {
        if (!valid) {
            // @ts-ignore
            ElNotification.warning({
                title: "Prompt information",
                message: "verification not success！",
                position: "bottom-right",
            });
            return;
        }

        const formData = new FormData()
        for (const [k, n] of Object.entries(formParam.value)) {
            if (n) {
                formData.append(k, n)
            }
        }
        await service.post("shipping/schedule/updatePortRotation", formData);
        // @ts-ignore
        ElNotification.success({
            title: "Prompt information",
            message: "save successful!",
            position: "bottom-right",
        });
        emit('saveOk')
    })
};
const cancelHandle = () => {
    emit('saveOk')
}

// 获取文件名称
function getFileName(name) {
    if (name == null) {
        return name;
    }
    // 如果是url那么取最后的名字 如果不是直接返回
    if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
    } else {
        return name;
    }
}

const arraySpanMethod = ({
    row,
    column,
    rowIndex,
    columnIndex,
}) => {
    if (columnIndex === 1) {
        if (rowIndex === 4||rowIndex === 5) {
            return [1, 5]
        }
    }
}
const handleUploadStart=(files)=> {
    console.log('开始上传:', files);
}
const handleFilesChange=(files)=> {
    formParam.value.fileName =files[0].name;
    formParam.value.file =files[0].file;        ;
}
const handleFileRemoved=(file,type)=> {
    if(file.url) {
        deleteFile(file,type)
    }
}
const deleteFile = (file,type) => {
    let params = {id:formParam.value.id,type:type,url: file.url }
    service.post(`shipping/schedule/deleteFile`, params).then(res=>{
        voyageSof.value=[]
        formParam.value.voyageSof = null;
        ElNotification.success({
            title: "Prompt information",
            message: "Delete successful!",
            position: "bottom-right",
        });
        emit('getDetail',formParam.value.id)
    })
}
</script>
<style lang="scss">
    .el-table__expand-column .cell {
        display: none;
    }

    .c-expand {
        color: #888;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        cursor: pointer;
        width: 100%;
        height: 100%;
    }

    .c-expand i {
        font-size: 16px;
    }

    .c-expand i.expand {
        font-size: 16px;
        transform: rotate(90deg);
        transition: all 0.25s;
    }
 

    ::v-deep(.el-table__header) {
        line-height: 48px !important;
        height: 48px;
    }

    .header-wrapper {
        border: 1px solid #ebeef5;
        border-bottom: none;
        padding: 10px;
    }

    .daf-table {
        margin: 0;
        padding: 0;
    }

    .tips {
        text-align: right;

        .el-button {
            margin-left: 10px;
            margin-right: 15px;
        }
    }

    .pane-footer {
        margin-top: 20px;
        text-align: right;
    }

</style>

<style lang="scss" scoped>

::v-deep(.handle_activity) {
        .select-trigger {
            .el-select__tags {
                .el-select-tags-wrapper  {
                    .el-tag {
                        i {
                            display: none;
                        }
                    }

                }

            }
    }
}

::v-deep(.berth_text) {
    .el-input__wrapper {
        .el-input__inner {
            text-align: center;
        }
    }
}
.upload-wrapper{
   border: 1px solid #d9d9d9;
   padding: 4px 10px;
   border-radius: 2px;
   >span{
    color: #04a9eb;
    font-size: 24px;
    margin-right: 2px;
   vertical-align: middle;
   margin-bottom: 2px;
   display: none;
   }
}
.upload-wrapper:hover{
   >span{
    display: inline-flex;
   }
   cursor: pointer;
}
</style>